package com.hejjon.core.utils;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

public class SerializeUtil {

    /**
     * 将Java对象序列号成字符串
     * @param obj
     * @return
     * @throws Exception
     */
    public static String serialize(Serializable obj) throws Exception {
        if (obj != null) {
            byte[] bytes = SerializationUtils.serialize(obj);
            return bytesToString(bytes);
        }
        return null;
    }


    public static byte[] stringToByte(String str) throws DecoderException {
        //转换成hex
        //return org.apache.commons.codec.binary.Hex.decodeHex(str);
        return org.apache.commons.codec.binary.Base64.decodeBase64(str);
    }


    public static String bytesToString(byte[] bytes) {
        //转换成hex
        // return org.apache.commons.codec.binary.Hex.encodeHexString(bytes);
        return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
    }

    /**
     * 将字符串反序列化为Java对象
     * @param str
     * @return
     * @param <T>
     * @throws Exception
     */
    public static <T extends Serializable> T deserialize(String str) throws Exception {
        if (StringUtils.isNotEmpty(str)) {
            return SerializationUtils.deserialize(stringToByte(str));
        }
        return null;
    }

    // 上述 serialize 和 deserialize 方法是可逆的
    //////////////////////////////////////////////////////////////////////////////////////////////////////




}
